import axios from 'axios'
import Vm from '../main'

/*
axios请求函数模块
参数注释: {
    gatwary: 请求源,
    apiPath: 请求路径,
    data: 带参,
    loading: 加载状态,
    method: 请求类型,
    contenType: 内容类型,
    header: 请求头信息,
    apiRs: 返回的数据,
    filePath: 文件的路径,
    formData: 表单参数
}
*/

export default class http {
    /**
     * 请求类型划分
     */
    // get请求
    static async get(gateway, apiPath, data, loading = true) {
        let apiRs = await this.apiRequest('GET', gateway, apiPath, data, 'application/json', loading)
        return this.bizExect(apiRs, apiPath)
    }

    // post发送表单请求
    static async postForm(gateway, apiPath, data, loading = true) {
        let apiRs = await this.apiRequest('POST', gateway, apiPath, data, 'application/x-www-form-urlencoded', loading)
        return this.bizExect(apiRs, apiPath)
    }

    // post发送json请求
    static async postJson(gateway, apiPath, data, loading = true) {
        let apiRs = await this.apiRequest('POST', gateway, apiPath, data, 'application/json', loading)
        return this.bizExect(apiRs, apiPath)
    }

    // post发送文件请求
    static async postFile(gateway, apiPath, filePath, formData) {
        let apiRs = await this.apiFileRequest(gateway, apiPath, filePath, formData)
        return this.bizExect(apiRs, apiPath)
    }

    // 请求文件方法
    static async apiFileRequest(gateway, apiPath, filePath, formData) {
        // 判断是否有停止指令
        let stopReq = false
        if (stopReq) {
            return {
                HttpCode: 423,
                Next: true,
                Code: 423,
                Msg: '正在登录中，放弃当前请求！',
                Data: null
            }
        }
        let url = this.getApiUrl(gateway, apiPath)
        return await this.fileUpload(url, filePath, formData)
    }
    // 上传请求
    static async fileUpload(url, filePath, formData) {
        if (!formData) {
            formData = {}
        }
        const uploadFile = () => {
            console.log('暂时没写')
        }
        // 上传文件方法，暂时没写
        const wpRes = await uploadFile({
            header: {
                'Req-Host': Vm.$store.state.common.extConfig.appId, // host
                'Xkd-Form': 'webapp',
                'Authorization': 'Bearer' + Vm.$store.state.common.jwtToken
            },
            url: url,
            formData: formData,
            filePath: filePath,
            name: 'webfile'
        })
        // res赋值处理
        let res = JSON.parse(wpRes.data)
        if (res) {
            res.HttpCode = wpRes.statusCode
            res.Next = true
        } else {
            res = {
                HttpCode: wpRes.statusCode,
                Code: wpRes.statusCode,
                Data: null,
                Next: true
            }
        }

        return res
    }
    /**
     * 请求类型划分结束
     */

    // 返回数据把关
    static bizExect(apiRs, apiPath) {
        apiRs.ApiPath = apiPath
        // 报错处理
        if (apiRs.domainerror) {
            apiRs.Next = false // 禁止继续请求下面的接口
            alert('请求域名配置错误')
            return apiRs
        }

        if (apiRs.HttpCode == 423) {
            apiRs.Next = false
            return apiRs
        }

        if (apiRs.HttpCode == 403) {
            apiRs.Next = false
            const returnUrl = this.getCurrentPageUrlWithArgs() // 获取返回的路由及参数
            this.$router.push({
                path: '/' +  Vm.$store.state.common.extConfig.storeId + '/pages/home/login?returnUrl=' + escape(returnUrl)
            })
            return apiRs
        }
        // 一切正常
        return apiRs
    }

    // 获取当前的路由及参数，并拼接
    static getCurrentPageUrlWithArgs() {
        let url = '/' + this.$route.path // 当前路由 /home
        const options = this.$route.params // 当前路由参数
        let urlWithArgs = ''
        for (let key in options) {
            const value = options[key]
            urlWithArgs += `${key}=${value}&`
        }
        if (urlWithArgs != '') {
            urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1)
            url = `${url}?${urlWithArgs}`
        }
        return url
    }

    // 封装axios
    static async webAxios(method, url, data, contenType, loading = true) {
        let config = Object
        if (method == 'GET') {
            config = {
                method: method,
                url: url,
                params: data,
                headers: this.getHeader(contenType)
            }
        } else {
            config = {
                method: method,
                url: url,
                data: data,
                headers: this.getHeader(contenType)
            }
        }
        
        if (loading) {
            // 正在加载，停止下面的接口
        }

        // 抓取报错信息，返回之 
        const wpRes = await axios(config).catch(err => {
            if (err && err.errMsg == 'request:fail url not in domain list') {
                return {
                    statusCode: 500,
                    domainerror: true
                }
            } else {
                throw (err)
            }
        })
        
        // 将返回的res进行处理
        let res = wpRes.data
        if (res) {
            res.HttpCode = wpRes.statusCode
            res.Next = true // 允许继续请求下面的接口
        } else {
            res = {
                HttpCode: wpRes.statusCode,
                Code: wpRes.statusCode,
                Data: null,
                Next: false, // 禁止继续请求下面的接口
                domainerror: wpRes.domainerror
            }
        }
        return res
    }

    // 拼接请求地址
    static getApiUrl(gateway, apiPath) {
        let baseUrl = Vm.$store.state.common.xkdApiDomians // xkdApiDomians        请求网域
        let storeId = Vm.$store.state.common.extConfig.storeId // extConfig.storeId    商铺id
        if (baseUrl[gateway]) {
            return `${baseUrl[gateway]}/${storeId}/${apiPath}`
        }
        return baseUrl.default+apiPath;
    }

    // 请求接口的方法
    static async apiRequest(method, gateway, apiPath, data, contenType, loading = true) {
        let stopReq = false
        // 判断是否有停止指令
        if (stopReq) {
            return {
                HttpCode: 423,
                Next: true,
                Code: 423,
                Msg: "正在登录中，放弃当前请求！",
                Data: null
            }
        }

        let url = this.getApiUrl(gateway, apiPath)
        return await this.webAxios(method, url, data, contenType, loading)
    }

    // 公共请求头
    static getHeader(contenType) {
        let headerData = {
            "Req-Host": Vm.$store.state.common.extConfig.appId, // 主机host
            // "From-Shopid": Vm.$store.state.common.VisitShopId,
            "Content-Type": contenType, // 内容类型：application/x-www-form-urlencoded/application/json
            // "Xkd-From": Vm.$store.state.common.extConfig.xkdFrom, // 流量来源
            "Xkd-From": 'weapp', // 流量来源
            "Authorization": 'Bearer ' + Vm.$store.state.common.jwtToken // 令牌
        }
        return headerData
    }
}